package gui;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

@SuppressWarnings("serial")
public class LuaChooser extends JFileChooser {
	private final static String SUFFIX = ".lua";
	
	public LuaChooser() {
		super();
		setFileFilter(new LuaFilter());
		setCurrentDirectory(new File(System.getProperty("user.dir")));
	}

	private class LuaFilter extends FileFilter {
		public boolean accept(File f) {
			return f.isDirectory() || hasValidSuffix(f);
		}

		public String getDescription() {
			return "Lua source files";
		}
	}
	
	public static boolean hasValidSuffix(File f) {
		return f.getName().toLowerCase().endsWith(SUFFIX);
	}
	
	public static File withValidSuffix(File f) {
		if (hasValidSuffix(f)) {
			return f;
		} else {
			String name = f.getName();
			int suffixStart = name.lastIndexOf('.');
			String strippedName = suffixStart < 0 ? name : name.substring(0, suffixStart);
			return new File(f.getParentFile(), strippedName + SUFFIX);
		}
	}
}
